<template>
    <div style="padding: 10px;">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form" v-if="searchFormVisible">
            <el-form-item label="客户姓名">
                <el-input v-model="searchForm.name" placeholder="请输入客户姓名" clearable />
            </el-form-item>
            <el-form-item label="客户手机号">
                <el-input v-model="searchForm.phone" placeholder="请输入客户手机号" clearable />
            </el-form-item>
            <el-form-item label="渠道来源">
                <el-select v-model="searchForm.channelId" placeholder="请选择渠道来源" clearable filterable
                    :loading="channelsLoading" style="width: 180px">
                    <el-option label="全部" :value="''" />
                    <el-option v-for="item in channels" :key="item.channelId" :label="item.channelName"
                        :value="item.channelId" />
                </el-select>
            </el-form-item>
            <el-form-item label="线索状态">
                <el-select v-model="searchForm.status" placeholder="线索状态" clearable style="width: 180px">
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="归属人">
                <el-input v-model="searchForm.owner" placeholder="请输入线索归属人" clearable />
            </el-form-item>
            <el-form-item label="跟进时间">
                <el-date-picker v-model="searchForm.dateRange" type="datetimerange" range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss"
                    @change="handleDateChange" style="width: 350px" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <div style="margin: 10px 0;" class="btn">
            <div>
                <el-button type="primary" @click="openDialog('add')" plain :icon="Plus">新增</el-button>
                <el-button type="success" :disabled="multipleSelection.length !== 1"
                    @click="openDialog('edit')" plain :icon="Edit">修改</el-button>
                <el-button type="danger" :disabled="multipleSelection.length === 0" @click="handleDelete" plain :icon="Delete">删除</el-button>
                <el-button type="warning" @click="handleExport" plain :icon="Download">导出</el-button>
            </div>
            <div>
                <el-tooltip class="box-item" effect="dark" content="隐藏搜索" placement="top">
                    <el-button :icon="Search" circle @click="searchFormVisible = !searchFormVisible" />
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="刷新" placement="top">
                    <el-button :icon="Refresh" circle @click="getClueData()" />
                </el-tooltip>


            </div>

        </div>

        <!-- 数据表格 -->
        <el-table :data="Data.tableData" border style="width: 100%" @selection-change="handleSelectionChange"
            @current-change="handleCurrentChange" highlight-current-row>
            <el-table-column type="selection" width="50" />
            <el-table-column prop="clueId" label="线索编号" width="90" />
            <el-table-column prop="name" label="客户姓名" width="100" />
            <el-table-column prop="phone" label="手机号" width="120" />
            <el-table-column prop="channelName" label="渠道来源" width="120" />
            <el-table-column prop="createTime" label="创建时间" width="170" />
            <el-table-column prop="owner" label="线索归属" width="100" />
            <el-table-column prop="status" label="线索状态" width="90">
                <template #default="scope">
                    <el-tag v-if="statusMap[scope.row.status]" type="info" effect="plain"
                        style="color: #409EFF; border-color: #b3d8ff; background: #f4faff;">
                        {{ statusMap[scope.row.status] }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="nextTime" label="下次跟进时间" width="170" />
            <el-table-column label="操作" width="120">
                <template #default="scope">
                    <el-link type="primary" @click="handleView(scope.row)" style="margin-right: 10px;">
                        <el-icon style="vertical-align: middle; margin-right: 2px;">
                            <View />
                        </el-icon>
                        查看
                    </el-link>
                    <el-link type="primary" @click="handleAssign(scope.row)">
                        <el-icon style="vertical-align: middle; margin-right: 2px;">
                            <UserFilled />
                        </el-icon>
                        分配
                    </el-link>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination background layout="total, prev, pager, next, jumper" :total="total"
            :page-size="searchForm.pageSize" :current-page="searchForm.pageNum" @current-change="handlePageChange"
            style="margin-top: 16px; text-align: right;" />

        <!-- 新增/编辑弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="resetDialogForm">
            <el-form :model="dialogForm" :rules="dialogRules" ref="dialogFormRef" label-width="100px"
                label-position="right">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone" required>
                            <el-input v-model="dialogForm.phone" placeholder="请输入手机号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户姓名" prop="name" required>
                            <el-input v-model="dialogForm.name" placeholder="请输入客户姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="渠道来源" prop="channelId">
                            <el-select v-model="dialogForm.channelId" placeholder="渠道来源" style="width: 100%">
                                <el-option v-for="item in channels" :key="item.channelId" :label="item.channelName"
                                    :value="item.channelId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="活动信息" prop="activity">
                            <el-select v-model="dialogForm.activityId" placeholder="活动信息" style="width: 100%">
                                <el-option v-for="item in activityList" :key="item.id" :label="item.name"
                                    :value="item.activityId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户性别" prop="gender">
                            <el-radio-group v-model="dialogForm.gender">
                                <el-radio :label="0">男</el-radio>
                                <el-radio :label="1">女</el-radio>
                                <el-radio :label="2">未知</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户年龄" prop="age">
                            <el-input-number v-model="dialogForm.age" :min="0" :max="120" controls-position="right"
                                style="width: 120px" />
                            <span style="margin-left: 8px;">年龄</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="微信号" prop="wechat">
                            <el-input v-model="dialogForm.weixin" placeholder="请输入微信号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="QQ号" prop="qq">
                            <el-input v-model="dialogForm.qq" placeholder="请输入QQ号" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitDialogForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 分配线索弹窗 -->
        <el-dialog v-model="assignDialogVisible" title="分配线索" width="600px" @close="resetAssignForm">
            <el-form :model="assignForm" :rules="assignRules" ref="assignFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="归属部门" prop="departmentId" required>
                            <el-tree-select v-model="assignForm.departmentId" :data="deptList" placeholder="请选择归属部门"
                                style="width: 100%" node-key="id" :props="{ label: 'label', children: 'children' }"
                                check-strictly :render-after-expand="false" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分配给" prop="deptId" required>
                            <el-select v-model="assignForm.deptId" placeholder="请选择用户" style="width: 100%">
                                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName"
                                    :value="item.userId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="assignDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAssignForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, nextTick, watch } from 'vue'
import { View, UserFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getClue, getCluechannels, getClueSummary, getClueActivity, addClue, updateClue, deleteClue, exportClue, getDeptTree, getUsersData, assignClue } from '@/api/clue/clue'
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Refresh,
    Plus,
    Download,
} from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'

const searchFormVisible = ref(true)
const searchForm = reactive({
    name: '',
    phone: '',
    channelId: '',
    status: '',
    owner: '',
    dateRange: [],
    params: {
        beginTime: '',
        endTime: '',
    },
    pageNum: 1,
    pageSize: 10
})
const getClueData = () => {
    getClue(searchForm).then(res => {
        console.log(res)
        Data.value.tableData = res.rows.map(item => {
            if (item.createTime && item.nextTime) {
                return {
                    ...item,
                    createTime: item.createTime.replace('T', ' '),
                    nextTime: item.nextTime.replace('T', ' ')
                }
            }
            return item
        })
        total.value = res.total
    })
}
getClueData()
const channels = ref([])
const channelsLoading = ref(false)
const getCluechannelsData = () => {
    channelsLoading.value = true
    getCluechannels().then(res => {
        channels.value = res.data || []
    }).finally(() => {
        channelsLoading.value = false
    })
}
getCluechannelsData()
const Data = ref({
    tableData: []
})
const total = ref(0)

const statusOptions = [
    { label: '全部', value: '' },
    { label: '已分配', value: '1' },
    { label: '跟进中', value: '2' },
    { label: '回收', value: '3' },
    { label: '伪线索', value: '4' },
    { label: '未知', value: '5' }
]

function handleSearch() {
    console.log(searchForm)
    getClueData()
    // 搜索逻辑
}
function handleReset() {
    Object.assign(searchForm, {
        name: '',
        phone: '',
        channelId: '',
        status: '',
        owner: '',
        dateRange: [],
        params: {
            beginTime: '',
            endTime: '',
        },
        pageNum: 1,
        pageSize: 10
    })
}
function handlePageChange(page) {
    console.log(page)
    searchForm.pageNum = page
    console.log(searchForm)
    getClueData()
    // 分页逻辑
}
function handleView(row) {
    console.log(row)
    // 查看逻辑
}
function handleAssign(row) {
    // console.log(row)
    assignForm.clueId = row.clueId
    console.log(assignForm)
    getDeptTree().then((res) => {
        deptList.value = res.data
    })
    assignDialogVisible.value = true
}
function handleDateChange(val) {
    if (val && val.length === 2) {
        searchForm.params.beginTime = val[0] || ''
        searchForm.params.endTime = val[1] || ''
        searchForm.dateRange[0] = val[0] || ''
        searchForm.dateRange[1] = val[1] || ''
    } else {
        searchForm.params.beginTime = ''
        searchForm.params.endTime = ''
        searchForm.dateRange = []
    }
}

const statusMap = {
    '1': '已分配',
    '2': '跟进中',
    '3': '回收',
    '4': '伪线索',
    '5': '未知'
}

const multipleSelection = ref([])
const currentRow = ref(null)

function handleSelectionChange(val) {
    multipleSelection.value = val
}
function handleCurrentChange(val) {
    currentRow.value = val
}

function handleDelete() {
    if (multipleSelection.value.length > 0) {
        const clueIds = multipleSelection.value.map(item => item.clueId).join(',')
        ElMessageBox.confirm(
            '确定要删除选中的' + clueIds + '吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            deleteClue(clueIds).then(res => {
                if (res.code === 200) {
                    ElMessage.success('删除成功')
                    getClueData()
                } else {
                    ElMessage.error('删除失败: ' + res.msg)
                }
            })
        }).catch(() => {
            // 用户取消，无需处理
        })
    }
}
function getClueSummaryData() {
    console.log(multipleSelection.value[0].clueId)
    return getClueSummary(multipleSelection.value[0].clueId).then((res) => {
        console.log(res)
        // 先清空再赋值，保持响应式
        Object.keys(dialogForm).forEach(key => delete dialogForm[key])
        Object.assign(dialogForm, res.data)
    })
}

const activityList = ref([])
function getClueActivityData() {
    if (!dialogForm.channelId) {
        activityList.value = []
        dialogForm.activity = ''
        return
    }
    getClueActivity(dialogForm.channelId).then((res) => {
        activityList.value = res.data || []
    })
}

const dialogVisible = ref(false)
const dialogTitle = ref('添加商机')
const dialogForm = reactive({
    phone: '',
    name: '',
    channelId: '',
    activity: '',
    gender: '',
    age: '',
    wechat: '',
    qq: ''
})
const dialogFormRef = ref(null)
const dialogRules = {
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }]
}
async function openDialog(type) {
    if (type === 'edit' && multipleSelection.value.length === 1) {
        dialogTitle.value = '编辑商机'
        await getClueSummaryData()
        dialogVisible.value = true
        nextTick(() => {
            if (dialogFormRef.value) dialogFormRef.value.clearValidate()
        })
    } else {
        dialogTitle.value = '添加商机'
        resetDialogForm()
        getClueActivityData()
        dialogVisible.value = true
        nextTick(() => {
            if (dialogFormRef.value) dialogFormRef.value.clearValidate()
        })
    }
}
function resetDialogForm() {
    Object.assign(dialogForm, {
        phone: '',
        name: '',
        channelId: '',
        activity: '',
        gender: '',
        age: '',
        wechat: '',
        qq: ''
    })
}
function submitDialogForm() {
    if (dialogTitle.value == '添加商机') {
        addClue(dialogForm).then((res) => {
            console.log(res)
            if (res.code === 200) {
                ElMessage.success('添加商机成功')
                dialogVisible.value = false
                getClueData()
            } else {
                ElMessage.error('添加商机失败', res.msg)
            }
        })
    } else if (dialogTitle.value == '编辑商机') {
        updateClue(dialogForm).then((res) => {
            console.log(res)
            if (res.code === 200) {
                ElMessage.success('编辑商机成功')
                dialogVisible.value = false
                getClueData()
            } else {
                ElMessage.error('编辑商机失败', res.msg)

            }
        })
    }
}
function handleExport() {
    const header = [
        '线索编号', '客户姓名', '手机号', '渠道来源', '创建时间', '线索归属', '线索状态', '下次跟进时间'
    ]
    const data = Data.value.tableData.map(item => [
        item.clueId,
        item.name,
        item.phone,
        item.channelName,
        item.createTime,
        item.owner,
        statusMap[item.status],
        item.nextTime
    ])
    const wsData = [header, ...data]
    const ws = XLSX.utils.aoa_to_sheet(wsData)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '线索数据')
    XLSX.writeFile(wb, '线索数据.xlsx')
}
watch(() => dialogForm.channelId, () => {
    console.log(dialogForm.channelId)
    getClueActivityData()
})

const assignDialogVisible = ref(false)
const assignForm = reactive({
    departmentId: '',
    deptId: '',
    clueId: ''
})
const assignFormRef = ref(null)
const assignRules = {
    departmentId: [{ required: true, message: '请选择归属部门', trigger: 'change' }],
    deptId: [{ required: true, message: '请选择用户', trigger: 'change' }]
}
const deptList = ref([])
const userList = ref([])

function resetAssignForm() {
    Object.assign(assignForm, { departmentId: '', deptId: '' })
}
function submitAssignForm() {
    assignFormRef.value.validate(valid => {
        if (valid) {
            // 提交分配逻辑
            const data = {
                assignId: assignForm.clueId,
                departmentId: assignForm.departmentId,
                deptId: assignForm.deptId,
                nickName: userList.value.find(item => item.userId === assignForm.deptId).nickName,
                type: 0,
                userId: userList.value.find(item => item.userId === assignForm.deptId).userId,
                userName: userList.value.find(item => item.userId === assignForm.deptId).userName,
            }
            assignClue(data).then((res) => {
                console.log(res)
                if (res.code === 200) {
                    ElMessage.success('分配成功')
                    assignDialogVisible.value = false
                } else {
                    ElMessage.error('分配失败', res.msg)
                }
            })
            assignDialogVisible.value = false
        }
    })
}

watch(() => assignForm.departmentId, (val) => {
    if (val) {
        console.log(val)
        getUsersData(val).then((res) => {
            console.log(res)
            userList.value = res.data
        })
    } else {
        userList.value = []
        assignForm.userId = ''
    }
})
</script>

<style scoped>
.search-form {
    margin-bottom: 16px;
}

.btn {
    display: flex;
    justify-content: space-between;
}
</style>